package com.fruit.controller.wap.index;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.goods.RightConfig;
import com.fruit.pojo.notice.NoticeMessage;
import com.fruit.pojo.recommend.Recommend;
import com.fruit.service.goods.GoodsManager;
import com.fruit.service.order.OrderManager;
import com.fruit.service.recommend.RecommendManager;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

import lombok.extern.slf4j.Slf4j;
/**
 * 首页controller <br/>
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "/")
public class WapIndexController extends BaseController {
	
	@Autowired
	private RecommendManager recommendManager;
	
	@Autowired
	private OrderManager orderManager;
	
	@Autowired
	private GoodsManager goodsManager;
	
	@Value("${h5_domain}")
	private String h5Domain;
	@Value("${domain}")
	private String domain;
	@Value("${top_domain}")
	private String topDomain;
	
	/**
	 * 微信支付回调 <br/>
	 * @param request request
	 * @param session session
	 * @return String
	 * @author shibeilei
	 * @version 2017.11.30 11:40
	 */
	@RequestMapping
	public String index(HttpServletRequest request, HttpSession session) {
		return "index";
	}
	
	@RequestMapping(value = "MP_verify_x9xQhKS8ajBg28ml.txt", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String mp(HttpServletRequest request, HttpSession session) {
		return "x9xQhKS8ajBg28ml";
	}	
	/**
	 * 登录校验<br/>
	 * 
	 * @param request
	 *            请求
	 * @param session
	 *            session
	 * @return Map<String, Object>
	 */
	@RequestMapping(value = "wap/checklogin", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> checkLogin(HttpServletRequest request, HttpSession session) {
		log.info("【验证登录】---【开始】--");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Integer userId = (Integer) session.getAttribute("userId");
			log.info("【验证登录】---【用户标识】--{}",userId);
			if (userId == null) {
				log.error("【验证登录】---【获取用户标识失败】");
				result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "获取用户登录异常!"));
				return result;
			}
			result.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "校验成功!"));
			log.info("【验证登录】---【操作成功】--【用户标识】--{}",userId);
		} catch (Exception e) {
			log.error("【验证登录】---【异常】---{}", e);
			result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		log.info("【验证登录】---【结束】--");
		return result;
	}
	
	/**
	 * 首页接口
	* @author 葛欢欢
	* @version 2017.11.30 16:40 
	* @param request
	* @param session
	* @return
	 */
	@RequestMapping(value = "wap/wapindex", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> wapindex(HttpServletRequest request, HttpSession session) {
		log.info("【首页】---【开始】--");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Map<String, Object> recommendMapIndexBanner = new HashMap<String, Object>();
			recommendMapIndexBanner.put("position", "indexBanner");
			List<Recommend> indexBanner = recommendManager.findRecommendByPosition(recommendMapIndexBanner);
			List<Recommend> goodsRecommendMiddle = recommendManager.getRecommendGoods("indexMiddle");//获取首页中间商品推荐信息（金饭碗）
			List<Recommend> goodsRecommendBotton = recommendManager.getRecommendGoods("indexBotton");//获取首页下面商品推荐信息
			if(goodsRecommendBotton.isEmpty()){
				resultMap.put("result", this.initResult(ResultInfo.SUCCESS, "ERROR", "没有推荐的商品"));
			}else{
				for(int i = 0; i<goodsRecommendBotton.size();i++){
					Recommend recommend = goodsRecommendBotton.get(i);
					String moth = recommend.getPickMoth();
					String year = DateUtil.getYear();
					String haveTime = recommend.getHarvestTime();
					if(StringUtils.isNotBlank(haveTime)){
						String mothStr = haveTime.substring(0,4);
						if(StringUtils.isNotBlank(moth)){
							if(year.equals(mothStr)){
								if(moth.startsWith("0")){
									recommend.setPickMoth(moth.substring(1, moth.length()) + "月");
								}else {
									recommend.setPickMoth(moth + "月");
								}
							}else{
								if(moth.startsWith("0")){
									recommend.setPickMoth(moth.substring(1, moth.length()) + "月 (" + mothStr + ")");
								}else {
									recommend.setPickMoth(moth + "月 (" + mothStr + ")");
								}
							}
						}else{
							recommend.setPickMoth("已采摘");
						}
					}else{
						recommend.setPickMoth("已采摘");
					}
					if(StringUtils.isNotBlank(recommend.getHarvestTime())){//如果当前时间 小于最小收获时间 那么采摘月份 显示首次采摘
						if(DateUtil.compareDate(recommend.getHarvestTime(), DateUtil.getDay())){
							recommend.setIsFirstPick("00");
						}else{
							recommend.setIsFirstPick("01");
						}
					}else{
						recommend.setIsFirstPick("00");
					}
					
				}
			}
			
			
			Map<String, Object> adoptionProcessRecommend = new HashMap<String, Object>();
			adoptionProcessRecommend.put("position", "adoptionProcess");
			List<Recommend> adoptionProcess = recommendManager.findRecommendByPosition(adoptionProcessRecommend);//wap首页认养流程
			List<NoticeMessage> getNotice = orderManager.getNotice();
			resultMap.put("goodsRecommendBotton", goodsRecommendBotton);
			resultMap.put("goodsRecommendMiddle", goodsRecommendMiddle);
			resultMap.put("indexBanner", indexBanner);
			resultMap.put("getNotice", getNotice);
			resultMap.put("adoptionProcess", adoptionProcess);
			resultMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "成功"));
		} catch (Exception e) {
			// TODO: handle exception
			log.error("【首页】-【异常】---{}", e);
			resultMap.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "网络繁忙"));
		}
		log.info("【首页】---【结束】--");
		return resultMap;
	}
	
	/**
	 * 链接
	* @author 葛欢欢
	* @version 2017.11.30 16:40 
	* @param request
	* @param session
	* @return
	 */
	@RequestMapping(value = "wap/config", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> config(HttpServletRequest request, HttpSession session) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("h5Domain", h5Domain);
		resultMap.put("domain", domain);
		resultMap.put("topDomain", topDomain);
		return resultMap;
	}
	
	/**
	 * 首页分类配置
	 * 
	 * @param request
	 *            request
	 * @param session
	 *            session
	 * @return Map<String, Object>
	 * @author 葛欢欢
	 * @version 2017.11.30 12:20
	 */
	@RequestMapping(value = "wap/rightConfig", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> rightConfig(HttpServletRequest request, HttpSession session) {
		long a = System.currentTimeMillis();
		log.info("【首页分类配置】---【开始】---");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<RightConfig> rc = goodsManager.getRightConfigList("01");
			if (rc.isEmpty()) {
				log.info("【首页分类配置】---【未查询到数据】---");
				resultMap.put("result", this.initResult(ResultInfo.ERROR, "no", "未查询到数据"));
				return resultMap;
			}
			resultMap.put("rightConfig", rc);
			resultMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		log.info("【获取权益配置】---【结束】---");
		log.info("【获取权益配置耗时】" + (System.currentTimeMillis() - a) / 1000f + "秒");
		return resultMap;
	}
	
}
